package cn.wolfcode.exception;

import cn.wolfcode.qo.JsonResult;
import com.alibaba.druid.support.json.JSONUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


//对控制器进行增强
@ControllerAdvice
public class ControllerAdviceForException {

//统一异常处理
    //告诉程序这个方法就是处理异常的,括号里是异常类型
    @ExceptionHandler(RuntimeException.class)
    public Object handlerExcetion(Model model, RuntimeException e, HttpServletResponse response , HandlerMethod method){
        e.printStackTrace();
        //如果用户访问的处理方法本来是视图的仙子也应该返回视图
        if (method.hasMethodAnnotation(ResponseBody.class)){
            response.setContentType("application/json;charset=utf-8");
            JsonResult jsonResult=new JsonResult(false,"操作失败，请联系管理员");
            try{
                response.getWriter().println(JSONUtils.toJSONString(jsonResult));
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return null;
        }else {
            model.addAttribute("message","异常");
            return "common/error";
        }
    }

    //捕获没有权限的异常处理
    @ExceptionHandler(UnauthorizedException.class)
    public Object handlerUnauthorizedException(Model model,RuntimeException e, HttpServletResponse response , HandlerMethod method){
        e.printStackTrace();
        //如果用户访问的处理方法本来是视图的仙子也应该返回视图
        if (method.hasMethodAnnotation(ResponseBody.class)){
            //利用响应对象输出json数据
            response.setContentType("application/json;charset=utf-8");
            JsonResult json=new JsonResult(false,"您没有操作权限");
            try{
                response.getWriter().println(JSONUtils.toJSONString(json));
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return null;
        }else {
            return "/common/nopermission";//错误实体
        }
    }

}
